package hikari.math;

import hikari.utils.Utils;
import org.swig.jirr.ISceneCollisionManager;
import org.swig.jirr.vector2di;
import org.swig.jirr.vector3df;

/**
 * @author Dmitry
 */
public class CircleCollider {
    private final CircleDrawer drawer;
    private vector2di vect1;
    private vector2di vect2;
    private final int mousecrossLength = 4;

    public CircleCollider(CircleDrawer drawer) {
        this.drawer = drawer;
    }

    private boolean intersectionLineWithMouseCross(vector2di start, vector2di end, int x, int y) {
        vector2di mouseNorth = new vector2di(x, y - mousecrossLength);
        vector2di mouseSouth = new vector2di(x, y + mousecrossLength);
        vector2di mouseWest = new vector2di(x - mousecrossLength, y);
        vector2di mouseEast = new vector2di(x + mousecrossLength, y);
        return Utils.lineHitTest(start, end, mouseNorth, mouseSouth)
                || Utils.lineHitTest(start, end, mouseWest, mouseEast);
    }

    public boolean isCollided(ISceneCollisionManager cm, int x, int y) {
        int count = drawer.getPointsCount();
        vector3df lastPoint = drawer.getPoint(drawer.getPointsCount() - 1);
        for (int i = 0; i < count; i++) {
            vector3df p = drawer.getPoint(i);
            vector2di p1 = cm.getScreenCoordinatesFrom3DPosition(lastPoint);
            vector2di p2 = cm.getScreenCoordinatesFrom3DPosition(p);
            if (intersectionLineWithMouseCross(p1, p2, x, y)) {
                vect1 = p1;
                vect2 = p2;
                return true;
            }

            lastPoint = p;
        }

        return false;
    }

    public boolean isCollidedFrontPart(ISceneCollisionManager cm, vector3df cameraPosition, int x, int y) {
        double lengthToCamera = cameraPosition.getDistanceFrom(drawer.getCenter());
        int count = drawer.getPointsCount();
        vector3df lastPoint = drawer.getPoint(drawer.getPointsCount() - 1);
        for (int i = 0; i < count; i++) {
            vector3df p = drawer.getPoint(i);
            double l = cameraPosition.getDistanceFrom(p);
            if (l < lengthToCamera) {
                vector2di p1 = cm.getScreenCoordinatesFrom3DPosition(lastPoint);
                vector2di p2 = cm.getScreenCoordinatesFrom3DPosition(p);
                if (intersectionLineWithMouseCross(p1, p2, x, y)) {
                    vect1 = p1;
                    vect2 = p2;
                    return true;
                }
            }

            lastPoint = p;
        }

        return false;
    }

    public vector2di getVect1() {
        return vect1;
    }

    public vector2di getVect2() {
        return vect2;
    }

}
